<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/07/18 12:37:27 $)
// $RCSfile: index.php,v $ : $Revision: 1.5 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


define("SWIFT_AREA", 140);

if (defined("SWIFTCUSTOMPATH"))
{
	chdir(SWIFTCUSTOMPATH);
} else {
	chdir('./../');
}

require_once ("./swift.php");
require_once ("./includes/functions_xml.php");
require_once ("./includes/functions_syncml.php");
$xml = new XML;
$syncml = new SyncML;

if (strstr("application/vnd.syncml+wbxml", strtolower($_SERVER["HTTP_ACCEPT"])) || $_SERVER["CONTENT_TYPE"] == "application/vnd.syncml+wbxml")
{
	$iswbxml = true;
} else {
	$iswbxml = false;
}

ob_start();


/**
* ###############################################
* Non Binary SyncML
* ###############################################
*/
if ($iswbxml == false && $_SERVER["CONTENT_TYPE"] == "application/vnd.syncml+xml")
{
	$debug .= "===============\nSyncML XML\n===============\n\n";
	//print_r($_SERVER);
	$debug .= implode("", file("php://input"));
	$requestResult = $syncml->parseRawRequest(implode("", file("php://input")));

	if (!$requestResult)
	{
		// Failed to parse the request XML
		$debug .= "Failed to parse!!\n";

		$contents = ob_get_contents();
		ob_end_clean();
		$fp = fopen("./files/test1.txt", "a+");
		fwrite($fp, $debug."===============\nOUTPUT\n===============\n\n".$contents);
		fclose($fp);

		exit;
	}

	
	$syncml->parseRequestHeader();
	
	// Send the required headers
	header ("Content-Type: application/vnd.syncml+xml");
	header ("Accept-Charset: ".$xml->charset);
	
	$debug .= "IP Is: ".$_SERVER["REMOTE_ADDR"]."\n";
	$debug .= "Source LOCURI Is: ".$syncml->requestHeaders["source_LocURI"]."\n";
	$debug .= "Source Session Id IS: ".$syncml->requestHeaders["sourcesessionid"]."\n";

	// Build the session id for this user
	$sessionid = md5($syncml->requestHeaders["source_LocURI"].$syncml->requestHeaders["sourcesessionid"]);

	$debug .= "Session ID Is: ".$sessionid."\n";
		
	// Do we have an existing session?
	$sessionresult = $session->startSyncMLSession($sessionid, $syncml->requestHeaders["source_LocURI"]);
	if (!$sessionresult && trim($syncml->requestCred["username"]) != "")
	{
		$debug .= "Session starting failed\n";

		// We dont have an existing session or session loading failed, but we have necessary credentials to login so try to authenticate and start a new session
		$staffid = $staffauth->authenticate($syncml->requestCred["username"], $syncml->requestCred["password"], true);
		if (!empty($staffid))
		{
			// Authentication successfull
			$session->insertSession(SESSION_SYNCML, $staffid, $sessionid);
			$syncml->addStatusCommand("0", "212");
			$debug .= "AuthenticatioN Successfull\n";
		} else {
			// Authentication Failed
			$syncml->addStatusCommand("0", "401");
			$debug .= "Authentication Failed";
		}

	} else if (!$sessionresult) {
		// Session starting failed and no credentials either, kill, kill now!
		$syncml->addStatusCommand("0", "407");
		$debug .= "No Credentials\n";
	} else if ($sessionresult == true) {
		// All went well, we have an existing session
		$syncml->addStatusCommand("0", "200");
		$debug .= "Session Started\n";
	} else {
		// Now what in the world could have happened in this case?!?
		$debug .= "Something went wrong";
	}

	$syncml->processCommands();


	// Prepeare the header
	$syncml->addResponseHeader();

	$debug .= "===============\nStarting XML Output\n===============\n\n";
	// Send the required xml data
	$xml->echoXML();
	echo SWIFT_CRLF.$xml->returnParentTag("SyncML", array("xmlns" => "SYNCML:SYNCML1.0"));

		echo $xml->returnParentTag("SyncHdr");
			echo $syncml->responseHeader;
		echo $xml->returnEndTag("SyncHdr");

		echo $xml->returnParentTag("SyncBody");
			echo $syncml->responseBody;
		//	if (trim($_SWIFT["sessionid"]) == "")
//			{
	//			$debug .= "No Session Id Exists, This is the final message\n";
				echo $xml->returnParentTag("Final");
				echo $xml->returnEndTag("Final");	
	//		} else {
		//		$debug .= "Session Id Exists, This is the NOT THE FINAL MESSAGE\n";			
//			}
		echo $xml->returnEndTag("SyncBody");


	echo $xml->returnEndTag("SyncML");




	

/**
* ###############################################
* Binary SyncML Response
* ###############################################
*/
} else if ($iswbxml == true) {
	require_once ("./includes/WBXML/Decoder.php");
	$decoder = new XML_WBXML_Decoder();
	unset($decoder->_wbxml2xml);

	$wbxmldata = implode("", file("php://input"));

	$debug .= "===============\nSyncML WBXML\n===============\n\n";
	echo $debug;
	echo $wbxmldata;

	echo "===============\n!! XML DATA !!\n===============\n\n";
	$xmldata = $decoder->decode($wbxmldata);
	echo $xmldata;


/**
* ###############################################
* Trying to access directly or..? Exit
* ###############################################
*/
} else {
	print_r($_SERVER);
//	trigger_error("Invalid SyncML Content Type, Unable to Continue", E_USER_ERROR);	
}


$contents = trim(ob_get_contents());
ob_end_clean();
$fp = fopen("./files/test1.txt", "a+");
fwrite($fp, $debug."===============\nOUTPUT\n===============\n\n".$contents);
fclose($fp);

echo $contents;
?>